﻿using System;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using System.Collections.Generic;
using System.Linq;

namespace HealthCommunity.Controls
{
	public partial class UCDrugStoreAdminMng : System.Web.UI.UserControl
	{
		private IUserProvider _UserProvider;
		private List<Role> lstRole;
		private IList<User> _DataSource;
		private int _TotalRecords;

		public IList<User> DataSourse
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				var u = SiteContext.Current.CurrentUser;

				if(u != null && u.Role != null && u.Role.RoleName.ToLower().Equals("storemanager"))
				{
					if(_UserProvider == null)
					{
						_UserProvider = new UserProvider();
					}

					var role = _UserProvider.GetAllRole();
					if(role != null && role.Count > 0)
					{
						var tempRole = role.Where(r => r.RoleName.ToLower() != "admin" && r.RoleName.ToLower() != "storemanager");

						if(tempRole != null)
						{
							lstRole = tempRole.ToList();
						}
					}

					var drugStoreProvider = new DrugStoreProvider();

					var drugStore = drugStoreProvider.GetDrugStore(u.DrugStoreID.GetValueOrDefault(0));

					List<User> lstUser = null;
					var tempData = _UserProvider.GetUserByDrugStore(drugStore.DrugStoreID, true, pageIndex, pageSize, out totalRecords);

					if(tempData != null)
					{
						var data = from us in tempData
											 where us.Role.RoleName.ToLower() != "admin" && us.Role.RoleName.ToLower() != "storemanager"
											 select us;

						if(data != null)
						{
							lstUser = data.ToList();
						}
					}

					_DataSource = lstUser;
				}
				else
				{
					if(!string.IsNullOrEmpty(ddlDrugStoreList.SelectedValue))
					{
						if(_UserProvider == null)
						{
							_UserProvider = new UserProvider();
						}

						lstRole = _UserProvider.GetAllRole();

						var selectedDrugStoreID = int.Parse(ddlDrugStoreList.SelectedValue);

						_DataSource = _UserProvider.GetUserByDrugStore(selectedDrugStoreID, true, pageIndex, pageSize, out totalRecords);
					}
				}

				this.TotalRecords = totalRecords;

				return _DataSource;
			}
		}

		public int PageIndex
		{
			get
			{
				if(ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = _DataSource == null ? this.DataSourse : _DataSource;

				if(data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if(totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if(totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if(totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return int.Parse(ddlPageSize.SelectedValue);
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				var u = SiteContext.Current.CurrentUser;

				if(u != null && u.Role != null && u.Role.RoleName.ToLower().Equals("storemanager"))
				{
					ddlDrugStoreList.Visible = false;
				}
				else
				{
					BindDrugStore();
				}

				hlCreateUser.Visible = u != null && u.Role != null && (u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager"));
				gvDrugStoreMember.Columns[gvDrugStoreMember.Columns.Count - 1].Visible = u != null && u.Role != null && (u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager"));
			}

			ltrMsg.Text = string.Empty;
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindDrugStoreMember();

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if(totalPages <= 25)
			{
				for(int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else
			{
				for(var i = 13; i > 0; i--)
				{
					if(indexs.Count >= 27)
					{
						break;
					}

					var index = currentPageIndex - i;

					if(index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}

				for(var i = 0; i <= 13; i++)
				{
					if(indexs.Count > 27)
					{
						break;
					}

					var index = currentPageIndex + i;

					if(index <= totalPages && index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}
			}

			this.RptrPageIndex.DataSource = indexs;
			this.RptrPageIndex.DataBind();

			this.LabelTotalPages.Text = totalPages.ToString();
			this.LabelTotalRecords.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if(RptrPageIndex.Items.Count > 0)
			{
				for(int i = 0; i < RptrPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RptrPageIndex.Items[i].FindControl("LBPageIndex") as LinkButton;

					if(thePagerIndexLink.Text.Trim().Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}
			}

			lbtnFirstPage.Enabled = (currentPageIndex > 0);

			lbtnLastPage.Enabled = totalPages > 1 && (currentPageIndex != totalPages - 1);
		}

		protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.PageIndex = 0;
		}

		protected void LBPageIndex_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch(e.CommandName)
			{
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//TotalRecords = DataSource.Count();

						BindDrugStoreMember();
					}
					break;
			}
		}

		protected void lbtnFirstPage_Click(object sender, EventArgs e)
		{
			PageIndex = 0;
			BindDrugStoreMember();
		}

		protected void lbtnLastPage_Click(object sender, EventArgs e)
		{
			PageIndex = TotalPages - 1;
			BindDrugStoreMember();
		}

		protected void gvDrugStoreMember_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if(e.CommandName.Equals("roleset"))
			{
				var userID = int.Parse(e.CommandArgument.ToString());

				if(_UserProvider == null)
				{
					_UserProvider = new UserProvider();
				}
				try
				{
					var u = _UserProvider.GetUser(userID, false);

					if(u != null)
					{
						var row = (GridViewRow)((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;

						if(row != null)
						{
							var ddlRoles = row.FindControl("ddlRoles") as DropDownList;

							if(ddlRoles != null)
							{
								var selectedRoleID = int.Parse(ddlRoles.SelectedValue);

								if(selectedRoleID != u.RoleID)
								{
									u.RoleID = selectedRoleID;

									if(_UserProvider.UpdateUser(u, false))
									{
										ltrMsg.Text = "设置成功";
									}
									else
									{
										ltrMsg.Text = "设置失败了";
									}
								}
							}
						}
					}
				}
				catch(Exception exc)
				{
					ltrMsg.Text = exc.Message;
				}
			}

			if(e.CommandName.Equals("remove"))
			{
				var userID = int.Parse(e.CommandArgument.ToString());

				if(_UserProvider == null)
				{
					_UserProvider = new UserProvider();
				}

				var theUser = _UserProvider.GetUser(userID, true);

				if(theUser != null)
				{
					theUser.UserState = (int)UserState.Deleted;

					if(_UserProvider.UpdateUser(theUser, false))
					{
						ltrMsg.Text = "删除成功";
					}
					else
					{
						ltrMsg.Text = "操作失败";
					}
				}
			}

			if(e.CommandName.Equals("removecomplete"))
			{
				var userID = int.Parse(e.CommandArgument.ToString());

				if(_UserProvider == null)
				{
					_UserProvider = new UserProvider();
				}

				if(_UserProvider.DeleteUser(userID))
				{
					ltrMsg.Text = "用户已彻底删除";
				}
				else
				{
					ltrMsg.Text = "操作失败";
				}
			}

			if(e.CommandName.Equals("detail"))
			{
				var userID = int.Parse(e.CommandArgument.ToString());
				Server.Transfer("~/UserDetail.aspx?userid=" + userID.ToString());
			}
		}

		protected void gvDrugStoreMember_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if(e.Row.DataItem != null)
			{
				var itemData = e.Row.DataItem as User;

				//var lbtnSetStoreAdmin = e.Row.FindControl("lbtnSetStoreAdmin") as LinkButton;
				var ltrSex = e.Row.FindControl("ltrSex") as Literal;
				var ddlRoles = e.Row.FindControl("ddlRoles") as DropDownList;

				if(itemData.Sex.Equals(1))
				{
					ltrSex.Text = "男";
				}
				else if(itemData.Sex.Equals(2))
				{
					ltrSex.Text = "女";
				}
				else if(itemData.Sex.Equals(0))
				{
					ltrSex.Text = "保密";
				}

				ddlRoles.DataSource = lstRole;
				ddlRoles.DataBind();

				if(itemData.Role != null && ddlRoles.Items != null && ddlRoles.Items.Count > 0)
				{
					ddlRoles.SelectedValue = itemData.RoleID.GetValueOrDefault(0).ToString();
				}
			}
		}

		protected void ddlDrugStoreList_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void BindDrugStoreMember()
		{
			var u = SiteContext.Current.CurrentUser;

			if(u != null && u.Role != null && u.Role.RoleName.ToLower().Equals("storemanager"))
			{
				if(_UserProvider == null)
				{
					_UserProvider = new UserProvider();
				}

				var role = _UserProvider.GetAllRole();
				if(role != null && role.Count > 0)
				{
					var tempRole = role.Where(r => r.RoleName.ToLower() != "admin" && r.RoleName.ToLower() != "storemanager");

					if(tempRole != null)
					{
						lstRole = tempRole.ToList();
					}
				}

				var drugStoreProvider = new DrugStoreProvider();

				var drugStore = drugStoreProvider.GetDrugStore(u.DrugStoreID.GetValueOrDefault(0));

				List<User> lstUser = null;
				var tempData = _UserProvider.GetUserByDrugStore(drugStore.DrugStoreID, true);

				if(tempData != null)
				{
					var data = from us in tempData
										 where us.Role.RoleName.ToLower() != "admin" && us.Role.RoleName.ToLower() != "storemanager"
										 select us;

					if(data != null)
					{
						lstUser = data.ToList();
					}
				}

				gvDrugStoreMember.DataSource = lstUser;
				gvDrugStoreMember.DataBind();
			}
			else
			{
				if(!string.IsNullOrEmpty(ddlDrugStoreList.SelectedValue))
				{
					if(_UserProvider == null)
					{
						_UserProvider = new UserProvider();
					}

					lstRole = _UserProvider.GetAllRole();

					var selectedDrugStoreID = int.Parse(ddlDrugStoreList.SelectedValue);

					gvDrugStoreMember.DataSource = _UserProvider.GetUserByDrugStore(selectedDrugStoreID, true);
					gvDrugStoreMember.DataBind();
				}
			}
		}

		private void BindDrugStore()
		{
			var drugStoreProvider = new DrugStoreProvider();

			ddlDrugStoreList.DataSource = drugStoreProvider.GetAllDrugStore();
			ddlDrugStoreList.DataBind();

			if(ddlDrugStoreList.Items != null && ddlDrugStoreList.Items.Count > 0)
			{
				ddlDrugStoreList.SelectedIndex = 0;
			}
		}
	}
}